package com.example.demo.controller;


import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.Article;
import com.example.demo.model.Board;
import com.example.demo.model.User;
import com.example.demo.services.IArticleService;
import com.example.demo.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/article")
@Slf4j
@Api(tags = "文章接口")
public class ArticleController {


    @Autowired
    private IArticleService articleService;
    @Autowired
    private IBoardService boardService;

    /**
     * 发布帖子
     * @param request
     * @param boardId
     * @param title
     * @param content
     * @return
     */

    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @ApiParam(value = "版块Id") @RequestParam(value = "boardId") @NonNull Long boardId,
                             @ApiParam(value = "⽂章标题") @RequestParam(value = "title") @NonNull String title,
                             @ApiParam(value = "帖⼦内容") @RequestParam(value = "content") @NonNull String content)
    {
        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        //是否被禁言
        if(user.getState()==1)
        {
            log.info("111");
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.toString());
        }

        Board board=boardService.selectById(boardId.longValue());
        if(board==null || board.getDeleteState()==1 || board.getState()==1)
        {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Article article=new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());

        articleService.create(article);

        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块ID") @RequestParam(value = "boardId",required = false)  Long boardId)
    {
        List<Article> articles=null;
        if(boardId==null)
        {
             articles= articleService.selectAll();
        }
        else {
            articles=articleService.selectByBoardId(boardId);
        }
       if(articles==null)
       {
           articles=new ArrayList<>();
       }
       //返回结果
        return AppResult.success(articles);
    }

    /**
     * 根据Id查询帖⼦详情
     *
     * @param id 版块Id
     * @return 指定Id的帖⼦详情
     */
    @ApiOperation("根据Id查询帖⼦详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,@ApiParam("帖子Id") @RequestParam("id") @NonNull Long id )
    {

        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);

        Article article=articleService.selectDetailById(id);
        if(article==null)
        {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断是否为作者
        if(user.getId()==article.getUserId())
        {
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @ApiOperation("编辑帖⼦")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam(value = "帖⼦Id") @RequestParam(value = "id") @NonNull Long id,
                            @ApiParam(value = "⽂章标题") @RequestParam(value = "title") @NonNull String title,
                            @ApiParam(value = "帖⼦内容") @RequestParam(value = "content") @NonNull String content) {


        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);

        //判断是否被禁言
        if(user.getState()==1)
        {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article=articleService.selectById(id);

        if (article == null)
        {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //查询是否是作者
        if(user.getId()!=article.getUserId())
        {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子状态
        if(article.getState()==1 || article.getDeleteState()==1)
        {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //调用service
        articleService.modify(id,title,content);

        log.info("帖子更新成功，Article id="+id+"User Id="+user.getId());
        return AppResult.success();
    }


    /**
     * 点赞
     *
     * @param id 帖⼦Id
     * @return AppResult
     */
    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam(value = "帖⼦Id") @RequestParam(value = "id") @NonNull Long id) {

        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);

        if(user.getState()==1)
        {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        articleService.thumbsUpById(id);
        return AppResult.success();
    }


    /**
     * 根据Id删除帖⼦
     *
     * @param id 帖⼦Id
     * @return
     */
    @ApiOperation("删除帖⼦")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request,
                                 @ApiParam("帖⼦Id") @RequestParam("id") @NonNull Long id)
    {

        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);

        //是否被禁言
        if(user.getState()==1)
        {
            //用户被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Article article=articleService.selectById(id);
        //判断帖子状态
        if (article == null || article.getDeleteState()==1)
        {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //查询是否是作者
        if(user.getId()!=article.getUserId())
        {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调⽤Service执⾏删除
        articleService.deleteById(id);

        return AppResult.success();
    }


    /**
     * 根据⽤⼾Id查询帖⼦列表
     *
     * @param userId ⽤⼾Id
     * @return 指定版块的帖⼦列表
     */
    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                    @ApiParam("用户Id") @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }
}
